const { Op } = require("sequelize");

const goodModel = appRequire('models/good');
const sequelize = appRequire('db');
const fs = require('fs');
const path = require('path')


// 导出对象，供其它模块调用
module.exports = {
    del,
};

async function del(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, [], request);
    if (checkResult == false) return;

    // 指定要读取的本地目录路径
    const rootDir = "D:/baiduasyncFileNew/BaiduSyncdisk/2024/03/53、2022年 花花艺树美学（20节PPT）";

    try {
        const allFiles = readFiles(rootDir); // 调用函数获取所有文件路径列表
        for (let item of allFiles) {
            let regex = /《(.*?)》/;
            var matchResult = item.match(regex);
            if (matchResult) {
                let folderPath = rootDir + "/" + matchResult[1]
                if (!fs.existsSync(folderPath)) fs.mkdirSync(folderPath);
                if (item.indexOf(matchResult[1]) != -1) {
                    let fileName = path.basename(item)
                    try {
                        if (item.indexOf("范画作品图") != -1) {
                            // 移动文件
                            fs.renameSync(item, rootDir + "/" + matchResult[1] + "/s.png")
                        } else if (item.indexOf("PPT预览图") != -1 || item.indexOf("批量输出为图片") != -1) {
                            // 移动文件
                            let nowPath = rootDir + "/" + matchResult[1] + "/l01" + ".png"
                            if (!fs.existsSync(nowPath)) fs.renameSync(item, nowPath)
                            else  fs.renameSync(item, rootDir + "/" + matchResult[1] + "/l02.png")
                        }
                    } catch (error) {
                        console.error(`文件移动失败：`, error);
                    }
                }
            } else {
                console.log("未能找到书名");
            }
        }
        console.log(allFiles)
        //console.log("All Files:", allFiles);
    } catch (err) {
        console.error("An error occurred while reading the files:", err);
    }

    returnData.data = true
    request.json(returnData)
}


function readFiles(dir) {
    const files = []; // 存放文件路径的数组

    try {
        const dirents = fs.readdirSync(dir, { withFileTypes: true }); // 同步读取目录内容

        for (let i = 0; i < dirents.length; i++) {
            if (dirents[i].isDirectory()) { // 如果当前项为目录
                const subDirPath = path.join(dir, dirents[i].name); // 获取子目录路径

                files.push(...readFiles(subDirPath)); // 递归调用自身处理子目录
            } else { // 如果当前项为文件
                const filePath = path.join(dir, dirents[i].name); // 获取文件路径

                files.push(filePath); // 将文件路径添加到结果数组中
            }
        }
    } catch (err) {
        console.error(`Error reading directory ${dir}:`, err);
    }

    return files;
}